package org.jorgen.openvino;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
@Component
public class Engine extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished (WebSocketSession session) throws Exception {
        log.info("websocket connected");
        this.session = session;
    }

    @Override
    public void handleTransportError (WebSocketSession session, Throwable exception) throws Exception {
        this.session = null;
        log.info("websocket failed");
    }

    @Override
    public void afterConnectionClosed (WebSocketSession session, CloseStatus status) throws Exception {
        this.session = null;
        log.info("websocket closed");
    }

    @PostConstruct
    public void initialize () throws Exception {
        new Thread(() -> {
            try {
                log.info("listening on 6666");
                server = new ServerSocket(6666);
                while (true) {
                    socket = server.accept();
                    log.info("socket connected");
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (true) {
                        var diff = reader.readLine();
                        if (diff == null)
                            break;
                        log.info("recv: {}", diff);
                        var ws = session;
                        if (ws != null) {
                            ws.sendMessage(new TextMessage(diff));
                            log.info("sent: {}", diff);
                        }
                    }
                    socket.close();
                    log.info("socket closed");
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private WebSocketSession session;
    private BufferedReader reader;
    private ServerSocket server;
    private Socket socket;
}
